package com.als.healthymananger.service.impl;

import com.als.healthymananger.dto.AppointmentDto;
import com.als.healthymananger.entity.Appointment;
import com.als.healthymananger.entity.Archive;
import com.als.healthymananger.mapper.AppointmentsMapper;
import com.als.healthymananger.service.AppointmentsService;
import com.als.healthymananger.service.ArchivesService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author aion
 * @since 2021-07-21
 */
@Service
public class AppointmentsServiceImpl extends ServiceImpl<AppointmentsMapper, Appointment> implements AppointmentsService {

    @Autowired
    private ArchivesService archivesService;

    @Override
    public boolean createAppointment(AppointmentDto appointment) {
        String archiveId = archivesService.generateArchiveId();

        // 实例化archive对象
        Archive archive = new Archive();
        archive.setUsername(appointment.getUsername());
        archive.setId(archiveId);
        archive.setName(appointment.getName());
        archive.setSex(appointment.getSex());
        archive.setIdentity(appointment.getIdentity());
        archive.setPhone(appointment.getPhone());
        archive.setNation(appointment.getNation());
        archive.setBirthday(appointment.getBirthday());
        archive.setMarry(appointment.getMarry());

        // 实例化appointment
        Appointment genAppointment = new Appointment();
        genAppointment.setType(appointment.getType());
        genAppointment.setDate(appointment.getDate());
        genAppointment.setEnable(appointment.getEnable());
        genAppointment.setArchivesId(archiveId);

        try {
            if (archivesService.save(archive))
                if (save(genAppointment)){
                    return true;
                }
            return false;
        } catch (Exception e){
            return false;
        }
    }

    @Override
    public AppointmentDto getAppointmentDto(int appointmentId) {
        AppointmentDto dto = baseMapper.getAppointmentById(appointmentId);
        return dto;
    }

    @Override
    public List<String>  getAppointmentDtoByUserName(String username) {
        List<Archive> list = archivesService.list(new QueryWrapper<Archive>().eq("username", username));

        List<String> apIds = list.stream().map(archive -> {
            Appointment appointment = getOne(new QueryWrapper<Appointment>().eq("archives_id", archive.getId()));
            if (appointment != null)
                return String.valueOf(appointment.getId());
            else
                return "00";
        }).filter(apId -> !apId.equals("00")).collect(Collectors.toList());

        return apIds;
    }
}
